# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from scrapy.http import HtmlResponse
from logging import getLogger
import requests,random
import time

class ScrapyseleniumjobSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class JdProductSeleniumMiddleware(object):
    '''用selenium爬取京东网站商品列表页面信息'''

    def __init__(self, timeout=None, service_args=[]):
        '''初始化，包括浏览器、参数等'''
        self.logger = getLogger(__name__)
        self.timeout = timeout
        #self.browser = webdriver.PhantomJS(service_args=service_args)
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--headless')
        chrome_options.add_argument('--load-images=false')
        chrome_options.add_argument('--disk-cache=true')
        self.browser = webdriver.Chrome(chrome_options=chrome_options)
        self.browser.set_window_size(1400, 700)
        self.browser.set_page_load_timeout(self.timeout)
        self.wait = WebDriverWait(self.browser, self.timeout)

        #设置代理池
        proxies = requests.get('http://api.xdaili.cn/xdaili-api//greatRecharge/getGreatIp?spiderId=6b7535399daf4ad8838bba029e176c31&orderno=YZ201871811160L5ypt&returnType=1&count=20').text
        self.proxy_list = proxies.strip("\r\n").split("\r\n")

    def __del__(self):
        '''析构函数，关闭浏览器'''
        self.browser.close()

    @classmethod
    def from_crawler(cls, crawler):
        '''根据配置参数创建爬虫'''
        return cls(timeout=crawler.settings.get('SELENIUM_TIMEOUT'),
                   service_args=crawler.settings.get('PHANTOMJS_SERVICE_ARGS'))

    def process_request(self, request, spider):
        '''
        模拟浏览器爬取京东网站商品列表页面
        :param request: Request对象
        :param spider: Spider对象
        :return: HtmlResponse
        '''
        
        #pro_addr = requests.get('http://api.xdaili.cn/xdaili-api//greatRecharge/getGreatIp?spiderId=6b7535399daf4ad8838bba029e176c31&orderno=YZ201871811160L5ypt&returnType=1&count=1').text
        #随机选取一个代理
        pro_addr = random.choice(self.proxy_list)
        request.meta['proxy'] = 'http://' + pro_addr
        print("正在使用代理"+pro_addr+"……")
        
        #self.logger.debug('PhantomJS is Starting')
        
        #获取要爬取第几页
        page = request.meta.get('page', 1)
        try:
            self.browser.get(request.url)
            #如果不是第一页，则模拟在网页的页面定位输入框输入页码，点击确定按钮
            if page > 1:
                input = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'input#page_jump_num')))
                submit = self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'div#J_bottomPage span.p-skip > a.btn.btn-default')))
                input.clear()
                input.send_keys(page)
                submit.click()

            #等待当前页的页码与要爬取页面的页码一致
            self.wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, 'div#J_bottomPage > span.p-num > a.curr'), str(page)))
            #等待商品列表清单出现
            self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div#plist > ul.gl-warp.clearfix > li.gl-item > div.gl-i-wrap.j-sku-item')))

            #执行javascript程序模拟将页面滚动移至底部操作
            time.sleep(1)
            for i in range(1, 4):
                self.browser.execute_script('window.scrollTo(0,document.body.scrollHeight)')            
                time.sleep(1)

            return HtmlResponse(url=request.url, body=self.browser.page_source, request=request, encoding='utf-8', status=200)

        except TimeoutException:
            return HtmlResponse(url=request.url, status=500, request=request)

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)
